const product = require('../../templates/product/list');

Page({
  data: {
    keyword: '',        // 搜索关键词
    width: 200,         // header宽度
    height: 64,         // header高度
    inputTop: 0,        // 搜索框距离顶部距离
    arrowTop: 0,        // 箭头距离顶部距离
    dropScreenH: 0,     // 下拉筛选框距顶部距离
    attrData: [],
    attrIndex: -1,
    dropScreenShow: false,
    scrollTop: 0,
    tabKey: 'dropdown', // 顶部筛选索引
    drawer: false,
    drawerH: 0,         // 抽屉内部scrollview高度
    selectedName: '综合',
    selectH: 0,
    sortOptions: {
      mutual: true,
      dropdown: [{
        name: '综合',
        selected: true,
        param: '',
        sort: '',
      }, {
        name: '收藏由少到多',
        selected: false,
        param: 'collect',
        sort: 'asc',
      }, {
        name: '收藏由多到少',
        selected: false,
        param: 'collect',
        sort: 'desc',
      }],
      alone: [{
        name: '销量',
        selected: false,
        param: 'sales',
        sort: null,
      }, {
        name: '价格',
        selected: false,
        param: 'price',
        sort: null,
      }, {
        name: '浏览',
        selected: false,
        param: 'view',
        sort: null,
      }]
    },
    attrArr: {
      label: {
        name: "标签",
        selected: false,
        selectedName: "标签",
        isActive: false,
        mutual: false,
        list: [{
          param: 'is_new',
          value: 1,
          name: '新品',
          selected: false
        }, {
          param: 'is_hot',
          value: 1,
          name: '热门',
          selected: false
        }, {
          param: 'is_recommend',
          value: 1,
          name: '推荐',
          selected: false
        }, {
          param: 'is_open_presell',
          value: 1,
          name: '预售',
          selected: false
        }, {
          param: 'is_integral',
          value: 1,
          name: '积分商品',
          selected: false
        }]
      },
      brand: {
        param: 'brand_id',
        name: "品牌",
        selected: false,
        selectedName: "品牌",
        isActive: false,
        mutual: true,
        list: []
      },
      category: {
        param: 'cate_id',
        name: "分类",
        selected: false,
        selectedName: "分类",
        isActive: false,
        mutual: true,
        list: []
      }
    },
    productList: [],
    pageIndex: 0,
    loading: false,
    noMore: false
  },
  onLoad: function (options) {
    let obj = wx.getMenuButtonBoundingClientRect();
    this.setData({
      urlParam: options.param || '',
      urlValue: options.val || '',
      keyword: options.keyword || '',
      width: obj.left,
      height: obj.top + obj.height + 8,
      inputTop: obj.top + (obj.height - 30) / 2,
      arrowTop: obj.top + (obj.height - 32) / 2,
      isList: wx.getStorageSync('rf_layout')['product']
    }, () => {
      wx.getSystemInfo({
        success: (res) => {
          this.setData({
            //略小，避免误差带来的影响
            dropScreenH: this.data.height * 750 / res.windowWidth + 186,
            drawerH: res.windowHeight - res.windowWidth / 750 * 100 - this.data.height
          });
        }
      });
    });
    this.initData();
    // this.getLabel();
    // this.getBrand();
    // this.getCategory();
  },
  onShow: function () {
    if (this.data.keyword) {
      this.getProduct();
    }
  },
  onPullDownRefresh: function () {
    this.setData({
      loading: true,
    }, () => {
      this.getProduct();
      wx.stopPullDownRefresh();
    });
  },
  initData: async function () {
    let attrArr = this.data.attrArr;
    let obj = [
      {api: 'product.brand', location: 'brand'},
      {api: 'product.category.common', location: 'category'}
    ];
    // 标签内容目前固定
    for (let item of attrArr.label.list) {
      if (this.data.urlParam == item.param) {
        item.selected = true;
        attrArr.label.isActive = true;
        attrArr.label.selected = true;
        attrArr.label.selectedName = item.name;
        break;
      }
    }
    // 获取品牌和类型数据
    for (let item of obj) {
      let res = await wx.util.request(item.api);
      let arr = [], attrSelected = false, attrName = '';
      if (this.data.urlParam == attrArr[item.location].param) {
        attrSelected = true;
      }
      for (let row of res) {
        let itemSelected = (attrSelected && this.data.urlValue == row.id);
        if (itemSelected) attrName = row.title;
        arr.push({
          value: row.id,
          name: row.title,
          selected: itemSelected
        });
      }
      attrArr[item.location].isActive = attrSelected;
      attrArr[item.location].selected = attrSelected;
      attrArr[item.location].selectedName = attrName;
      attrArr[item.location].list = arr;
    }
    this.setData({
      attrArr: attrArr
    }, () => {
      this.getProduct(false);
    });
  },
  /*getLabel: function () {
    let label = this.data.attrArr.label;
    for (let item of label.list) {
      if (this.data.urlParam == item.param) {
        item.selected = true;
        label.isActive = true;
        label.selected = true;
        label.selectedName = item.name;
        break;
      }
    }
    this.setData({
      [`attrArr.label`]: label
    });
  },
  getBrand: function () {
    wx.util.request('product.brand').then(res => {
      let arr = [], attrSelected = false, attrName = '';
      if (this.data.urlParam == this.data.attrArr.brand.param) {
        attrSelected = true;
      }
      for (let item of res) {
        let itemSelected = (attrSelected && this.data.urlValue == item.id);
        if (itemSelected) attrName = item.title;
        arr.push({
          value: item.id,
          name: item.title,
          selected: itemSelected
        });
      }
      this.setData({
        [`attrArr.brand.isActive`]: attrSelected,
        [`attrArr.brand.selected`]: attrSelected,
        [`attrArr.brand.selectedName`]: attrName,
        [`attrArr.brand.list`]: arr
      });
    }).catch(err => {
      console.log(err);
    });
  },
  getCategory: function () {
    wx.util.request('product.category.common').then(res => {
      let arr = [], attrSelected = false, attrName = '';
      if (this.data.urlParam == this.data.attrArr.category.param) {
        attrSelected = true;
      }
      for (let item of res) {
        let itemSelected = (attrSelected && this.data.urlValue == item.id);
        if (itemSelected) attrName = item.title;
        arr.push({
          value: item.id,
          name: item.title,
          selected: itemSelected
        });
      }
      this.setData({
        [`attrArr.category.isActive`]: attrSelected,
        [`attrArr.category.selected`]: attrSelected,
        [`attrArr.category.selectedName`]: attrName,
        [`attrArr.category.list`]: arr
      });
    }).catch(err => {
      console.log(err);
    })
  },*/
  getProduct: function (reset = true) {
    let attrArr = this.data.attrArr;
    let sortArr = this.data.sortOptions[this.data.tabKey];
    let curPage = reset ? 1 : this.data.pageIndex + 1;
    let queryData = {
      page: curPage,
      keyword: this.data.keyword
    };
    // 遍历搜索条件
    for (let key in attrArr) {
      if (!attrArr[key].selected) continue;
      if (!attrArr[key].param) {
        // label的param是跟随list中的项目存在
        for (let child of attrArr[key].list) {
          if (child.selected) {
            queryData[child.param] = child.value;
            if (attrArr[key].mutual) break;
          }
        }
      } else {
        // 取值
        if (attrArr[key].list.length > 0) {
          // list.length > 0
          for (let child of attrArr[key].list) {
            if (child.selected) {
              // queryData[attrArr[key].param] = child.value;
              // if (attrArr[key].mutual) break;
              if (attrArr[key].mutual) {
                queryData[attrArr[key].param] = child.value;
                break;
              } else {
                if (queryData[attrArr[key].param]) {
                  queryData[attrArr[key].param] += `,${child.value}`;
                } else {
                  queryData[attrArr[key].param] = child.value;
                }
              }
            }
          }
        } else {
          // list.length == 0
          queryData[attrArr[key].param] = attrArr[key].value;
        }
      }
    }
    // 遍历搜索排序
    for (let item of sortArr) {
      if (!item.param || !item.sort) continue;
      if (item.selected) {
        queryData[item.param] = item.sort;
      }
    }
    // 如果本次查询条件与上一次完全一致则返回
    if (this.data.queryData == JSON.stringify(queryData)) return;
    // 查询商品
    wx.util.request('', {body: queryData}).then(res => {
      let list = reset ? [] : this.data.productList;
      for (let item of res) {
        // 仅提取展示数据
        /*let obj = {
          id: item.id,
          picture: item.picture,
          name: item.name,
          price: item.price,
          market_price: item.market_price,
          sales: item.sales
        };*/
        list.push(item);
      }
      //list.push.apply(list, res);
      this.setData({
        loading: false,
        productList: list,
        pageIndex: curPage,
        noMore: res.length < 10,
        noData: res.length == 0,
        queryData: JSON.stringify(queryData)
      });
    }).catch(err => {
      console.log(err);
    });
  },
  onReachBottom: function () {
    if (this.data.noMore) return;
    this.setData({
      loading: true,
    }, () => {
      this.getProduct(false);
    });
  },
  btnDropChange: function (e) {
    let index = e.currentTarget.dataset.index;
    let attrArr = this.data.attrArr;
    let attrItem = attrArr[index];
    let attrIdx = this.data.attrIndex;
    let arr = JSON.parse(JSON.stringify(attrItem.list));
    // let isActive = `attrArr[${index}].isActive`;
    if (arr.length === 0) {
      this.setData({
        [`attrArr.${index}.isActive`]: !attrItem.isActive,
        [`attrArr.${index}.selected`]: !attrItem.selected,
        [`attrArr.${index}.value`]: attrItem.name
      });
      // 刷新商品列表
      this.getProduct();
    } else {
      // 遍历属性数组，确保在切换下拉框时原有样式不变
      for (let i in attrArr) {
        let item = attrArr[i];
        item.isActive = item.selected;
        if (i == index) {
          // 修改当前被点击的下拉框样式
          item.isActive = false;
          // 收回时保持原有样式
          if (attrIdx == index) {
            item.isActive = item.selected;
          }
        }
      }
      this.setData({
        attrData: attrItem, //arr,
        attrIndex: (attrIdx == index ? -1 : index), // index
        dropScreenShow: (attrIdx == index ? !this.data.dropScreenShow : true),  // true
        //[isActive]: (attrIdx == index ? attr.selected : false),  // false
        attrArr: attrArr
      }, () => {
        this.setData({
          scrollTop: 0
        });
      });
    }
  },
  btnSelected: function (e) {
    let mutual = e.currentTarget.dataset.mutual;
    let index = e.currentTarget.dataset.index;
    let list = this.data.attrData.list;
    // 互斥选项则唯一
    if (mutual) {
      for (let i in list) {
        if (i == index) {
          list[i].selected = !list[i].selected;
        } else {
          list[i].selected = false;
        }
      }
    } else {
      list[index].selected = !list[index].selected;
    }
    this.setData({
      [`attrData.list`]: list
      //[`attrData[${index}].selected`]: !this.data.attrData[index].selected
    });
  },
  reset: function () {
    let attrArr = this.data.attrArr;
    let attrData = this.data.attrData;
    for (let i in attrArr) {
      if (attrData.name == attrArr[i].name) {
        attrArr[i].isActive = false;
        attrArr[i].selected = false;
      }
    }
    if (attrData.list) {
      for (let item of attrData.list) {
        item.selected = false;
      }
    }
    this.setData({
      attrArr: attrArr,
      attrData: attrData,
      keyword: ''
    }, () => {
      this.getProduct();
    });
  },
  btnCloseDrop: function () {
    let idx = this.data.attrIndex;
    let attrArr = this.data.attrArr;
    attrArr[idx].isActive = attrArr[idx].selected;
    this.setData({
      scrollTop: 0,
      dropScreenShow: false,
      attrIndex: -1,
      attrArr: attrArr
      //[`attrArr[${idx}].isActive`]: this.data.attrArr[idx].selected
    });
  },
  btnSure: function () {
    let index = this.data.attrIndex;
    let list = this.data.attrData.list;
    let active = false, attrName = '';
    let attrItem = `attrArr.${index}`;
    for (let item of list) {
      if (item.selected) {
        active = true;
        attrName += attrName ? ";" + item.name : item.name
      }
    }
    this.setData({
      [`${attrItem}.list`]: list,
      [`${attrItem}.isActive`]: active,
      [`${attrItem}.selected`]: active,
      [`${attrItem}.selectedName`]: attrName
    }, () => {
      // 刷新商品
      this.getProduct();
    });
    this.btnCloseDrop();
  },
  showDropdownList: function () {
    this.setData({
      selectH: 246
    });
  },
  hideDropdownList: function () {
    this.setData({
      selectH: 0
    });
  },
  dropdownItem: function (e) {
    let index = e.currentTarget.dataset.index;
    let arr = this.data.sortOptions.dropdown;
    for (let i in arr) {
      if (i == index) {
        arr[i].selected = true;
      } else {
        arr[i].selected = false;
      }
    }
    this.setData({
      [`sortOptions.dropdown`]: arr,
      selectedName: arr[index].name,
      selectH: 0
    }, () => {
      this.getProduct();
    });
  },
  screen: function (e) {
    let layout = wx.getStorageSync('rf_layout'),
        data = this.data,
        isList = !data.isList,
        dataset = e.currentTarget.dataset,
        key = dataset.key;
    layout.product = isList;
    wx.setStorageSync('rf_layout', layout);
    if (key == 'style') {
      this.setData({
        isList: isList
      });
    } else if (key == 'dropdown') {
      if (data.tabKey != key) {
        this.setData({
          tabKey: 'dropdown'
        }, () => {
          this.getProduct();
        });
      } else {
        if (this.data.selectH > 0) {
          this.hideDropdownList();
        } else {
          this.showDropdownList();
        }
      }
    } else {
      let list = data.sortOptions[key], index = dataset.index;
      for (let i in list) {
        list[i].selected = false;
        if (i == index) {
          list[i].selected = true;
          list[i].sort = (list[i].sort == 'asc' ? 'desc' : 'asc');
        }
      }
      this.setData({
        tabKey: 'alone',
        [`sortOptions.${key}`]: list
      }, () => {
        this.getProduct();
      });
    }
  },
  closeDrawer: function () {
    this.setData({
      drawer: false
    });
  },
  search: function () {
    let pages = getCurrentPages(),
        prevPage = pages[pages.length - 2];
    if (prevPage.route.indexOf('search/index') > -1) {
      wx.navigateBack();
      return;
    }
    wx.navigateTo({
      url: '../search/index',
    });
  },
  detail: function (e) {
    product.detail(e);
  },
  back: function() {
    if (this.data.drawer) {
      this.closeDrawer();
    } else {
      wx.navigateBack();
    }
  },
})